// pages/bookingGoods/addressVip/index/index.js
var call = require("../../../../utils/request.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageStatus: false,
    listData: [], // 数据
    status: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getListData() // 获取数据
  },
  // 拿取当前地址
  takeIt(e) {
    let obj =  e.currentTarget.dataset.obj
    let pages = getCurrentPages(); //获取当前页面js里面的pages里的所有信息。
    let prevPage = pages[pages.length - 2];
    let address = `${obj.province}${obj.city}${obj.area}${obj.address}`
    let address_id = obj.id
    prevPage.setData({
      address,
      address_id,
      source: 2,
    })
    wx.navigateBack({
      delta: 1,
      success: function () {
        if (prevPage.route == 'pages/bookingGoods/confirm/index') {
          prevPage.getAddress() //这个函数式调用接口的函数
          prevPage.getDistributionFee() // 获取配送费
        }
      }
    })
  },
  // 获取数据
  getListData () {
    wx.showLoading({
      title: '加载中...',
    });
    call.getData('/api/book_order/address', {},
      res => {
        console.log(res.data)
        if(res.code == 1){
          let listData = []
          for(let item of res.data){
            if(item.source != 1){
              listData.push(item)
            }
          }
          console.log(listData)
          this.setData({ listData })
        }else{
          wx.showToast({ icon: 'none',title: res.msg })
        }
        this.setData({pageStatus: true})
        wx.hideLoading();
      },
      err => {
        console.log(err)
      },false)
  },
  // 返回上一页
  goReturn: function () {
    let pages = getCurrentPages(); //获取当前页面js里面的pages里的所有信息。
    let prevPage = pages[pages.length - 2]; 
    wx.navigateBack({
      delta: 1
    })
  },
  // 添加地址
  goAdd () {
    wx.navigateTo({
      url: '/pages/bookingGoods/addressVip/add/index'
    })
  },
  // 编辑地址
  goEdit (e) {
    console.log(e.target.dataset.obj)
    let obj = e.target.dataset.obj
    wx.navigateTo({
      url: '/pages/bookingGoods/addressVip/edit/index?obj=' + JSON.stringify(obj)
    })
  },
  // 删除地址
  goDelete (e) {
    let id = e.target.id
    let index = e.target.dataset.index
    let that = this
    console.log(e.target.dataset.index)
    wx.showModal({
      title: '提示',
      content: '是否删除此地址？',
      success (res) {
        if (res.confirm) {
          call.request('/api/ship_address/del', { id },
          res => {
            
            if(res.code == 1){
              console.log(index,that.data.listData)
              that.data.listData.splice(index,1)
              that.setData({ listData: that.data.listData })
            }else{
              wx.showToast({ icon: 'none',title: res.msg })
            }
          },
          err => {
            console.log(err)
          },false)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  }
})